<?php
/**
 * Created by muniao.
 * User: muniao
 * Date: 2018/7/25
 * Time: 9:48
 */

namespace app\api\controller\android\v1;


use app\api\model\Authority;
use app\index\model\Pdf;
use think\Cache;
use think\Controller;
use think\Exception;
use think\Request;
use foxyZeng\huyi\HuYiSMS;

class Order extends Controller
{
    protected $model;
    protected $us;
    protected $newTime;
    protected $endTime;
    protected $overtime;
    protected $pdf;

    public function _initialize()
    {
        $this->model    = new Authority();
        $this->pdf      = new Pdf();
        $this->us       = $this->model->check(1);
        $this->newTime  = strtotime(date("Y-m-d H:i:s", strtotime(date("Y-m-d H:i:s") . " -5 minutes")));
        $this->endTime  = strtotime(date("Y-m-d H:i:s", strtotime(date("Y-m-d H:i:s") . " -10 minutes")));
        $this->overtime = strtotime(date("Y-m-d H:i:s", strtotime(date('Y-m-d H:i:s', strtotime('+1minute')))));
    }

    /**
     * 发布订单
     * cate_id 二级id
     */
    public function send_need()
    {

        $data = $this->model->post(['channel_id', 'pro_id', 'province_id', 'city_id', 'county_id', 'addres', 'contacts', 'telephone', 'remarks', 'logo', 'lat', 'lng']);

        if (!is_mobile($data['telephone'])) {
            r_date([], 300, '请输入正确的手机号');
        }
        if (empty($data['addres'])) {
            r_date([], 300, '请输入详细地址');
        }
        if (empty($data['contacts'])) {
            r_date([], 300, '请输入联系人姓名');
        }
        if (empty($data['pro_id'])) {
            r_date([], 300, '不能为空');
        }
        if (empty($data['channel_id'])) {
            r_date([], 300, '不能为空');
        }
        if ($data['province_id']) {
            $province = db('province')->where(['province' => ['like', "%{$data['province_id']}%"]])->value('province_id');
        }
        if ($data['city_id']) {
            $city_id = db('city')->where(['city' => ['like', "%{$data['city_id']}%"]])->value('city_id');
        }
        if ($data['county_id']) {
            $county = db('county')->where(['county' => ['like', "%{$data['county_id']}%"]])->value('county_id');
        }

        $user = [
            'channel_id' => $data['channel_id'],//渠道
            'order_no' => order_sn(),//订单号
            'pro_id' => $data['pro_id'],//一级问题
            'province_id' => $province,//省
            'city_id' => $city_id,//市
            'county_id' => $county,//区
            'addres' => $data['addres'],//地址
            'contacts' => $data['contacts'],//联系人
            'telephone' => $data['telephone'],//联系电话
            'remarks' => $data['remarks'],//备注
            'logo' => !empty($data['logo']) ? serialize(json_decode($data['logo'], true)) : '',//图片
            'state' => 1,//待指派
            'assignor' => $this->us['user_id'],//指派人
            'created_time' => time(),//创建时间
            'update_time' => time(),//创建时间
            'lat' => $data['lat'],//创建时间
            'lng' => $data['lng'],//创建时间
        ];

        $res = db('order')->insertGetId($user);

        if ($res) {
            db('remind')->insertGetId([
                'admin_id' => $this->us['user_id'],
                'order_id' => $res,
                'time' => time(),
                'stater' => 1,
                'tai' => 1,
            ]);
            r_date([], 200, '新增成功');
        }
        r_date([], 300, '新增失败');

    }

    /**
     * @throws Exception
     * 提醒个数
     */
    public function Unread()
    {

        $coun1 = db('remind')->where(['admin_id' => $this->us['user_id'], 'stater' => 1, 'tai' => 1])->count();
        $coun2 = db('remind')->where(['admin_id' => $this->us['user_id'], 'stater' => 2, 'tai' => 1])->count();
//        $coun3 = db('remind')->where(['admin_id' =>  $this->us['user_id'], 'stater' => 3, 'tai' => 1])->count();
//        $coun4 = db('remind')->where(['admin_id' =>  $this->us['user_id'], 'stater' => 4, 'tai' => 1])->count();
//        $coun5 = db('remind')->where(['admin_id' =>  $this->us['user_id'], 'stater' => 5, 'tai' => 1])->count();
//        $coun6 = db('remind')->where(['admin_id' =>  $this->us['user_id'], 'stater' => 7, 'tai' => 1])->count();


        $couns = [
            'zhu' => [
                0 => $coun1,
                1 => $coun2,
            ]
        ];

        r_date($couns, 200);


    }

    /**
     * 修改地址
     * cate_id 二级id
     */
    public function edit_di()
    {
        $data = $this->model->post(['order_id', 'province_id', 'city_id', 'county_id', 'addres']);
        if ($data['province_id']) {
            $province = db('province')->where(['province' => ['like', "%{$data['province_id']}%"]])->value('province_id');
        }
        if ($data['city_id']) {
            $city_id = db('city')->where(['city' => ['like', "%{$data['city_id']}%"]])->value('city_id');
        }
        if ($data['county_id']) {
            $county = db('county')->where(['county' => ['like', "%{$data['county_id']}%"]])->value('county_id');
        }
        $o   = [
            'province_id' => $province,//省
            'city_id' => $city_id,//市
            'county_id' => $county,//区
            'addres' => $data['addres'],//地址
        ];
        $res = db('order')->where('order_id', $data['order_id'])->update($o);

        if ($res) {
            r_date([], 200, '新增成功');
        }
        r_date([], 300, '新增失败');

    }

    /**
     * 获取渠道
     */
    public function get_my_qu()
    {
        $res = db('chanel')->field('id,title')->where('type', 2)
            ->select();
        r_date($res);
    }

    /**
     * 获取问题
     */
    public function get_my_wen()
    {
        $res = db('goods_category')
            ->field('goods_category.title,goods_category.id')
            ->where(['pro_type' => 1, 'is_enable' => 1, 'parent_id' => 0])
            ->select();
        r_date($res);
    }

    /**
     * 获取项目一级标题
     */
    public function get_my_ge()
    {
        $data = Request::instance()->post(['page' => 1, 'limit' => 10]);
        $res  = db('product_chan')
            ->where(['parents_id' => 0, 'pro_types' => 1])
            ->field('product_title,product_id')
            ->select();
        foreach ($res as $k => $v) {
            $res[$k]['count'] = db('product_chan')->where(['parents_id' => $v['product_id'], 'pro_types' => 1])->count();
        }
        $re['tao']      = 0;
        $re['detailed'] = $res;

        $rdetailed = db('detailed')->where(['detaileds_id' => 0])->field('detailed_id,detailed_title')->page($data['page'], $data['limit'])->select();
        foreach ($rdetailed as $k => $v) {
            $rdetailed[$k]['count'] = db('detailed')->where(['detaileds_id' => $v['detailed_id']])->count();
        }
        $r['tao']      = 1;
        $r['detailed'] = $rdetailed;
        $data          = [
            0 => $re,
            1 => $r,
        ];
        r_date($data);
    }

    /**
     * 获取项目二级标题
     */
    public function get_my_er()
    {
        $data = Request::instance()->post(['type', 'detailed', 'page', 'limit']);
        if ($data['type'] == 0) {

            $rdetailed = db('product_chan')->where(['parents_id' => $data['detailed'], 'pro_types' => 1])->join('unit un', 'un.id=product_chan.units_id', 'left')->field('product_id,product_title,parents_id,un.title,prices')->page($data['page'], $data['limit'])->select();
            foreach ($rdetailed as $k => $l) {
                $pr[$k]['projectId']    = $l['product_id'];
                $pr[$k]['projectMoney'] = $l['prices'];
                $pr[$k]['projectTitle'] = $l['product_title'];
                $pr[$k]['title']        = $l['title'];
                $pr[$k]['tao']          = 0;
                unset($rdetailed[$k]);
            }
        } elseif ($data['type'] == 1) {

            $rdetailed = db('detailed')->where(['detaileds_id' => $data['detailed'], 'tao' => 0])->join('unit un', 'un.id=detailed.un_id', 'left')->field('detailed_id,detailed_title,detaileds_id,un.title,artificial')->page($data['page'], $data['limit'])->select();
            foreach ($rdetailed as $k => $l) {
                $pr[$k]['projectId']    = $l['detailed_id'];
                $pr[$k]['projectMoney'] = $l['artificial'];
                $pr[$k]['projectTitle'] = $l['detailed_title'];
                $pr[$k]['title']        = $l['title'];
                $pr[$k]['tao']          = 1;
                unset($rdetailed[$k]);
            }
        }
        r_date($pr);
    }

    /**
     * 基建赠送项目
     */
    public function get_zeng()
    {
        $res = db('product_chan')->where(['parents_id' => ['neq', 0], 'pro_types' => 1])->join('unit un', 'un.id=product_chan.units_id', 'left')->field('product_title,parents_id,un.title,prices')->order('product_id desc')->select();
        foreach ($res as $k => $l) {

            $pr[$k]['projectMoney'] = $l['prices'];
            $pr[$k]['projectTitle'] = $l['product_title'];
            $pr[$k]['title']        = $l['title'];
            $pr[$k]['tao']          = 0;
            unset($res[$k]);
        }
        $rdetailed = db('detailed')->where(['detaileds_id' => ['neq', 0]])->join('unit un', 'un.id=detailed.un_id', 'left')->field('detailed_title,detaileds_id,un.title,artificial')->order('detailed_id desc')->select();
        foreach ($rdetailed as $k => $l) {
            $pr1[$k]['projectMoney'] = $l['artificial'];
            $pr1[$k]['projectTitle'] = $l['detailed_title'];
            $pr1[$k]['title']        = $l['title'];
            $pr1[$k]['tao']          = 1;
            unset($rdetailed[$k]);
        }

        $data = array_merge($pr1, $pr);
        r_date($data);
    }

    /**
     * 基建搜索
     */
    public function despair()
    {
        $data = $this->model->post(['con']);
        $list = db('detailed')->field('detailed.detailed_title,detailed.detailed_id,detailed.artificial,un.title,detailed.tao')->where(['detaileds_id' => ['neq', 0], 'detailed_title' => ['like', "%{$data['con']}%"]])->join('unit un', 'un.id=detailed.un_id', 'left')->order('detailed_id desc')->select();
        foreach ($list as $k => $l) {

            $pr[$k]['tao']          = 1;
            $pr[$k]['projectId']    = $l['detailed_id'];
            $pr[$k]['projectMoney'] = $l['artificial'];
            $pr[$k]['projectTitle'] = $l['detailed_title'];
            $pr[$k]['title']        = $l['title'];
            $pr[$k]['tao2']         = $l['tao'];

            unset($list[$k]);
        }
        r_date($pr);
    }

    /**
     * 基检搜索
     */
    public function set_jian()
    {

        $data = $this->model->post(['tao', 'detailed', 'sou1']);
        $s    = substr($data['detailed'], 0, -1);  //利用字符串截取函数消除最后一个逗号
        if ($data['tao'] == 0) {
            $product = db('product_chan')->where('product_id', 'in', $s)->field('parents_id,product_id,product_title')->select();
            foreach ($product as $o) {
                $product_chan = db('product_chan')->join('unit u', 'product_chan.units_id=u.id', 'left')->where(['product_id' => $o['product_id'], 'parents_id' => $o['parents_id']])->field('product_title,prices,u.title,product_title,product_id')->select();
                foreach ($product_chan as $k => $l) {
                    $pr[$k]['projectId']    = $l['product_id'];
                    $pr[$k]['projectMoney'] = $l['prices'];
                    $pr[$k]['projectTitle'] = $l['product_title'];
                    $pr[$k]['title']        = $l['title'];
                    $pr[$k]['tao']          = 0;
                    unset($product_chan[$k]);
                }
                $s   = [
                    'big_title' => db('product_chan')->where(['product_id' => $o['parents_id']])->value('product_title'),
                    'data' => $pr,
                    'tao' => 0,
                ];
                $p[] = $s;

            }
            r_date($p, 200);

        } elseif ($data['tao'] == 1) {
            if (!empty($data['detailed'])) {

                $product = db('detailed')->where(['detailed_id' => ['in', $s]])->field('detaileds_id,detailed_id')->select();
                foreach ($product as $o) {
                    $product_chan = db('detailed')->join('unit u', 'detailed.un_id=u.id', 'left')->where(['detailed_id' => $o['detailed_id'], 'detaileds_id' => $o['detaileds_id']])->field('detailed_id,detailed_title,artificial,u.title')->select();
                    foreach ($product_chan as $k => $l) {
                        $pr[$k]['projectId']    = $l['detailed_id'];
                        $pr[$k]['projectMoney'] = $l['artificial'];
                        $pr[$k]['projectTitle'] = $l['detailed_title'];
                        $pr[$k]['title']        = $l['title'];
                        $pr[$k]['tao']          = 1;
                        unset($product_chan[$k]);
                    }
                    $s   = [
                        'big_title' => db('detailed')->where(['detailed_id' => $o['detaileds_id']])->value('detailed_title'),
                        'data' => $pr,
                        'tao' => 1,
                    ];
                    $p[] = $s;
                }

            }
            if (!empty($data['sou1'])) {
                $s = substr($data['sou1'], 0, -1);  //利用字符串截取函数消除最后一个逗号
                $m = explode(",", $s);

                foreach ($m as $h) {
                    $pro  = db('product_chan')->where(['product_title' => $h])->field('parents_id,product_id')->find();
                    $pk[] = $pro;
                }
                foreach ($pk as $o) {
                    $produ = db('product_chan')->join('unit u', 'product_chan.units_id=u.id', 'left')->where(['product_id' => $o['product_id'], 'parents_id' => $o['parents_id']])->select();
                    foreach ($produ as $k => $l) {
                        $kl[$k]['projectId']    = $l['product_id'];
                        $kl[$k]['projectMoney'] = $l['prices'];
                        $kl[$k]['projectTitle'] = $l['product_title'];
                        $kl[$k]['title']        = $l['title'];
                        $kl[$k]['tao']          = 0;
                        unset($produ[$k]);
                    }
                    $s    = [
                        'big_title' => db('product_chan')->where(['product_id' => $o['parents_id']])->value('product_title'),
                        'tao' => 0,
                        'data' => $kl,
                    ];
                    $p1[] = $s;
                }
            }
            if (!empty($data['sou1']) && !empty($data['detailed'])) {
                r_date(array_merge($p, $p1), 200);
            } elseif (!empty($data['detailed'])) {
                r_date($p, 200);
            } elseif (!empty($data['sou1'])) {
                r_date($p1, 200);
            }
        } elseif ($data['tao'] == 2) {
            $object = db('information')->where(['id' => ['in', $s], 'types' => 1, 'user_id' => $this->us['user_id']])->field('id,class_a,class_b,company,square,un_Price,zhi,fen')->select();
            foreach ($object as $o) {
                $product_chan = db('information')->where(['id' => $o['id'], 'types' => 1, 'user_id' => $this->us['user_id']])->field('id,class_a,class_b,company,square,un_Price,zhi,fen')->select();
                foreach ($product_chan as $k => $l) {
                    $pr[$k]['projectId']    = $l['id'];
                    $pr[$k]['projectMoney'] = $l['un_Price'];
                    $pr[$k]['projectTitle'] = $l['class_b'];
                    $pr[$k]['title']        = $l['company'];
                    $pr[$k]['tao']          = 2;
                    unset($product_chan[$k]);
                }
                $s   = [
                    'big_title' => $l['class_a'],
                    'data' => $pr,
                    'tao' => 2,
                ];
                $p[] = $s;
            }
            r_date($p, 200);
        }


    }


    /**
     * 基检编辑
     */
    public function updaty()
    {
        $data = Request::instance()->post();
        db()->startTrans();
        try {
            if ($data['fen'] == 0) {
                $product_chan = db('product_chan')->where('product_id', $data['projectId'])->find();
                $title        = db('unit')->where('id', $product_chan['units_id'])->value('title');
                $user         = [
                    'company' => !empty($title) ? $title : '',//单位
                    'square' => $data['square'],//方量
                    'un_Price' => $product_chan['prices'],//单价
                    'rule' => $product_chan['price_rules'],//规则
                    'zhi' => $data['zhi'],//规则
                    'to_price' => $product_chan['prices'] * $data['square'],//总价
                    'class_b' => $product_chan['product_title'],//三
                    'projectId' => $data['projectId'],//三
                    'class_a' => db('product_chan')->where(['product_id' => $product_chan['parents_id']])->value('product_title'),//三
                ];
            } elseif ($data['fen'] == 1) {
                $detailed = db('detailed')->where('detailed_id', $data['projectId'])->find();
                $title    = db('unit')->where('id', $detailed['un_id'])->value('title');
                $user     = [
                    'company' => !empty($title) ? $title : '',//单位
                    'square' => $data['square'],//方量
                    'un_Price' => $detailed['artificial'],//单价
                    'rule' => $detailed['rmakes'],//规则
                    'zhi' => $data['zhi'],//规则
                    'to_price' => $detailed['artificial'] * $data['square'],//总价
                    'class_b' => $detailed['detailed_title'],//三
                    'projectId' => $data['projectId'],//三
                    'class_a' => db('detailed')->where(['detailed_id' => $detailed['detaileds_id']])->value('detailed_title'),//三
                ];

            } elseif ($data['fen'] == 2) {
                $user = [
                    'company' => $data['company'],//单位
                    'square' => $data['square'],//方量
                    'un_Price' => $data['prices'],//单价
                    'to_price' => $data['square'] * $data['prices'],//总价
                    'zhi' => $data['zhi'],//规则
                    'class_b' => $data['class_b'],//三
                    'class_a' => $data['class_a'],//三
                ];
            }


            $uss['problem']       = '';
            $uss['code']          = '';
            $uss['store_code_id'] = $data['capital_id'];
            $uss['title']         = $data['class_b'];
            $uss['category']      = $data['class_a'];
            $uss['unit']          = $data['prices'];
            $uss['quantity']      = $data['square'];
            $uss['price']         = $user['to_price'];
            $da                   = send_post(UIP_SRC . "/shopowner/Order/updateOrderProblem", $uss);
            $results              = json_decode($da);
            if ($results->code != 200) {
                db()->rollback();
                r_date(null, 300);
            }
            $res1 = db('capital')->where(['capital_id' => $data['capital_id']])->field('ordesr_id,to_price')->find();
            $r    = db('order')->where(['order_id' => $res1['ordesr_id']])->field('ification,order_id')->find();
            if ($r['ification'] == 2) {
                $ca     = db('envelopes')->where(['ordesr_id' => $r['order_id']])->field('give_money')->find();
                $cap    = db('capital')->where(['ordesr_id' => $r['order_id'], 'types' => 1, 'enable' => 1])->sum('to_price');
                $amount = $cap - $res1['to_price'] + $user['to_price'];
                $p      = $ca['give_money'];
            } else {
                $ca     = db('capital')->where(['ordesr_id' => $r['order_id'], 'types' => 1, 'enable' => 1])->field('sum(to_price),sum(give_money)')->find();
                $amount = $ca['sum(to_price)'] - $res1['to_price'] + $user['to_price'];
                $p      = $ca['sum(give_money)'];
            }

            if (($amount * 0.1) < $p) {
                r_date(null, 300, '优惠金额不能大于订单总价的10%');
            }
            $p3 = db('capital')->where(['capital_id' => $data['capital_id']])->update($user);
            if ($data['yc'] == 1) {
                $res2 = db('capital')->where(['ordesr_id' => $res1['ordesr_id'], 'enable' => 1, 'programme' => 3, 'types' => 1])->sum('to_price');
                db('through')->where(['order_ids' => $res1['ordesr_id'], 'baocun' => 1])->update(['amount' => $res2]);
            }
            $cap = db('order')->where(['order_id' => $res1['ordesr_id']])->field('ification,planned,appointment')->find();
            $this->pdf->put($res1['ordesr_id'], 1,$cap);
            if ($p3) {
                db()->commit();
                r_date(null, 200);
            }
        } catch (Exception $e) {
            db()->rollback();
            r_date(null, 300, $e->getMessage());
        }

    }

    /**
     * 基检增项
     */
    public function amplification()
    {
        $data = Request::instance()->post();
        db()->startTrans();
        try {
            $order = db('order')->where('order_id', $data['order_id'])->field('ification,order_no')->find();
            if ($data['yc'] == 1) {
                $programme = 3;
            } else {
                $programme = 1;
            }
            if ($order['ification'] == 1) {
                $capital = db('capital')->where(['ordesr_id' => $data['order_id'], 'types' => 1, 'enable' => 1, 'programme' => 1])->order('capital_id desc')->find();
                $give_a  = $capital['give_a'];//三
                $give_b  = $capital['give_a'];//三
                $wen_a   = $capital['wen_a'];//一级分类
                $wen_b   = $capital['wen_b'];//二
                $wen_c   = $capital['wen_c'];//二
            } else {
                $give_a = '';//三
                $give_b = '';//三
                $wen_a  = '';//一级分类
                $wen_b  = '';//二
                $wen_c  = '';//二
            }
            if ($data['company']) {
                $op       = json_decode($data['company']);
                $op       = $this->object2array($op);
                $user_arr = [];
                foreach ($op as $ke => $v) {
                    if ($v['types'] == 0) {
                        $product_chan = db('product_chan')->where('product_id', $v['product_id'])->find();
                        $users        = [
                            'wen_a' => $wen_a,
                            'wen_b' => $wen_b,
                            'wen_c' => $wen_c,
                            'company' => $v['unit'],//单位
                            'square' => $v['fang'],//方量
                            'un_Price' => $product_chan['prices'],//单价
                            'rule' => $product_chan['price_rules'],//规则
                            'zhi' => $v['zhi'],//质保
                            'types' => 1,//状态
                            'fen' => 0,//状态
                            'to_price' => $product_chan['prices'] * $v['fang'],//总价
                            'crtime' => time(),
                            'ordesr_id' => $data['order_id'],
                            'class_a' => $v['title'],//三
                            'class_b' => $v['projectTitle'],//三
                            'enable' => 1,//三
                            'programme' => $programme,//三
                            'give_a' => $give_a,//赠送项目
                            'give_b' => $give_b,
                            'projectId' => $v['product_id'],//三
                        ];

                    } elseif ($v['types'] == 1) {
                        $product_chan = db('detailed')->where('detailed_id', $v['product_id'])->find();
                        $users        = [
                            'wen_a' => '',
                            'wen_b' => '',
                            'wen_c' => '',
                            'company' => $v['unit'],//单位
                            'square' => $v['fang'],//方量
                            'un_Price' => $product_chan['artificial'],//单价
                            'rule' => $product_chan['rmakes'],//规则
                            'zhi' => $v['zhi'],//质保
                            'types' => 1,//状态
                            'fen' => 1,//状态
                            'to_price' => $product_chan['artificial'] * $v['fang'],//总价
                            'crtime' => time(),
                            'ordesr_id' => $data['order_id'],
                            'class_a' => $v['title'],//三
                            'class_b' => $v['projectTitle'],//三
                            'qi_rmakes' => '',
                            'enable' => 1,//三
                            'programme' => $programme,//三
                            'give_a' => $give_a,//赠送项目
                            'give_b' => $give_b,
                            'projectId' => $v['product_id'],//三
                        ];

                    } elseif ($v['types'] == 2) {
                        $users = [
                            'wen_a' => '',
                            'wen_b' => '',
                            'wen_c' => '',
                            'company' => $v['unit'],//单位
                            'square' => $v['fang'],//方量
                            'un_Price' => $v['prices'],//单价
                            'ordesr_id' => $data['order_id'],
                            'rule' => '',//规则
                            'zhi' => $v['zhi'],//质保
                            'types' => 1,//状态
                            'fen' => 2,//状态
                            'to_price' => $v['fang'] * $v['prices'],//总价
                            'crtime' => time(),
                            'class_a' => $v['title'],//三
                            'class_b' => $v['projectTitle'],//三
                            'qi_rmakes' => '',
                            'enable' => 1,//三
                            'programme' => $programme,//三
                            'give_a' => $give_a,//赠送项目
                            'give_b' => $give_b,
                        ];

                    }

                    $cap                                  = db('capital')->insertGetId($users);
                    $uss                                  = [];
                    $uss['order_num']                     = $order['order_no'];
                    $uss['problem'][$ke]['problem']       = '';
                    $uss['problem'][$ke]['code']          = '';
                    $uss['problem'][$ke]['store_code_id'] = $cap;
                    $uss['problem'][$ke]['title']         = $v['projectTitle'];
                    $uss['problem'][$ke]['category']      = $v['title'];
                    $uss['problem'][$ke]['unit']          = $v['unit'];
                    $uss['problem'][$ke]['quantity']      = $v['fang'];
                    $uss['problem'][$ke]['price']         = $users['to_price'];
                    $user_arr[]                           = $uss;
                }

                send_post(UIP_SRC . "/shopowner/Order/editOrderProblem", $user_arr);
            }
            $cap = db('order')->where(['order_id' => $data['order_id']])->field('ification,planned,appointment')->find();
            $this->pdf->put($data['order_id'], 1,$cap);
            if ($data['yc'] == 1) {
                $WeChat = 0;
                $s      = '';
                $res1   = db('capital')->where(['ordesr_id' => $data['order_id'], 'enable' => 1, 'programme' => 3, 'types' => 1])->field('capital_id,to_price')->select();
                foreach ($res1 as $item) {
                    $WeChat += $item['to_price'];
                    $s      .= $item["capital_id"] . ',';
                }
                $s = substr($s, 0, -1);
                db('through')->where(['order_ids' => $data['order_id'], 'baocun' => 1])->update(['amount' => $WeChat, 'capital_id' => $s]);
            }
            db()->commit();
            r_date([], 200);
        } catch (Exception $e) {
            db()->rollback();
            r_date([], 300, $e->getMessage());
        }
    }

    /**
     * 基检删除
     */
    public function del()
    {
        $data = Request::instance()->post();
        db()->startTrans();
        try {
            $res1     = db('capital')->where(['capital_id' => $data['capital_id']])->field('ordesr_id')->find();
            $to_price = db('capital')->where(['ordesr_id' => $res1['ordesr_id'], 'types' => 1, 'enable' => 1])->sum('to_price');
            $order    = db('order')->where('order_id', $res1['ordesr_id'])->field('ification')->find();
            if ($order['ification'] == 2) {
                $give_money = db('envelopes')->where(['ordesr_id' => $res1['ordesr_id']])->field('give_money')->find();
                if ($to_price < $give_money['give_money']) {
                    r_date([], 300);
                }
                db('capital')->where(['capital_id' => $data['capital_id']])->update(['types' => 2]);
            } else {
                $capital = db('capital')->where(['capital_id' => $data['capital_id'], 'types' => 1])->field('give_money')->find();
                if ($to_price < $capital['give_money']) {
                    r_date([], 300);
                }
                if ($capital['give_money'] != 0) {
                    db('capital')->where(['capital_id' => $data['capital_id']])->update(['types' => 2]);
                    $capital_id = db('capital')->where(['ordesr_id' => $data['order_id'], 'types' => 1])->field('capital_id')->order('capital_id desc')->find();
                    db('capital')->where(['capital_id' => $capital_id['capital_id']])->update(['give_money' => $capital['give_money']]);
                } else {
                    db('capital')->where(['capital_id' => $data['capital_id']])->update(['types' => 2]);
                }
            }
            if ($data['yc'] == 1) {
                $res2 = db('capital')->where(['ordesr_id' => $res1['ordesr_id'], 'enable' => 1, 'programme' => 3, 'types' => 1])->sum('to_price');
                db('through')->where(['order_ids' => $res1['ordesr_id'], 'baocun' => 1])->update(['amount' => $res2]);
            }
            $cap = db('order')->where(['order_id' => $res1['ordesr_id']])->field('ification,planned,appointment')->find();

            $this->pdf->put($res1['ordesr_id'], 1,$cap);
            $uss['store_code_id'] = $data['capital_id'];
            $da                   = send_post(UIP_SRC . "/shopowner/Order/delOrderProblem", $uss);
            $results              = json_decode($da);
            if ($results->code != 200) {
                db()->rollback();
                r_date(null, 300);
            }
            db()->commit();
            r_date([], 200);
        } catch (Exception $e) {
            db()->rollback();
            r_date([], 300, $e->getMessage());
        }
    }

    /**
     * 基检跟新公共
     */
    public function up()
    {
        $data  = Request::instance()->post();
        $order = db('order')->where('order_id', $data['ordesr_id'])->field('ification')->find();
        db()->startTrans();
        if ($order['ification'] == 2) {
            $oi = [
                'wen_a' => $data['wen_a'],//一级分类
                'give_b' => substr($data['give_b'], 0, -1),//一级分类
                'gong' => $data['gong'],
                'give_remarks' => $data['give_remarks'],//备注
                'give_money' => $data['give_money'],//优惠金额
                'capitalgo' => !empty($data['capitalgo']) ? serialize(json_decode($data['capitalgo'], true)) : '',//图片
            ];
            db('envelopes')->where('envelopes_id', $data['envelopes_id'])->update($oi);
        } else {
            $capital = substr($data['capital'], 0, -1);
            $capital = explode(',', $capital);
            foreach ($capital as $k) {
                $cap = db('capital')->where(['capital_id' => $k, 'types' => 1, 'enable' => 1])->field('give_money')->find();
                if ($cap['give_money'] != 0) {
                    $oi = [
                        'give_money' => $data['give_money'],
                        'capitalgo' => !empty($data['capitalgo']) ? serialize(json_decode($data['capitalgo'], true)) : '',
                        'give_b' => !empty($data['give_b']) ? $data['give_b'] : '',
                        'gong' => $data['gong'],
                        'give_remarks' => $data['give_remarks'],
                    ];
                    db('capital')->where(['capital_id' => $k, 'types' => 1, 'enable' => 1])->update($oi);
                } else {
                    $oi = [
                        'capitalgo' => !empty($data['capitalgo']) ? serialize(json_decode($data['capitalgo'], true)) : '',
                        'give_b' => !empty($data['give_b']) ? $data['give_b'] : '',
                        'gong' => $data['gong'],
                        'give_remarks' => $data['give_remarks'],//备注
                    ];
                    db('capital')->where(['capital_id' => $k, 'types' => 1, 'enable' => 1])->update($oi);
                }

            }
        }
        $uss['order_id'] = $data['ordesr_id'];
        $uss['discount'] = $oi['give_money'];
        $result          = send_post(UIP_SRC . "/shopowner/Order/editOrder", $uss);
        $results         = json_decode($result);

        if ($results->code == 200) {
            db()->commit();
            $cap = db('order')->where(['order_id' => $data['ordesr_id']])->field('ification,planned,appointment')->find();
            $this->pdf->put($data['ordesr_id'], 1,$cap);
            r_date(null, 200);
        }

        db()->rollback();
        r_date(null, 300);


    }

    /**
     * 电子合同
     */
    public function sign()
    {

        $data = Request::instance()->post();
        $op   = db('sign')->where(['order_id' => $data['order_id'], 'user_id' => $this->us['user_id']])->find();
        if ($op) {
            $sign = [
                'idnumber' => $data['idnumber'],
                'username' => $data['username'],
                'order_id' => $data['order_id'],
                'user_id' => $this->us['user_id'],
                'addtime' => strtotime($data['addtime']),
                'uptime' => strtotime($data['uptime']),
                'addres' => $data['addres'],
                'ding' => 0,
                'zhong' => 0,
                'wei' => 0,
                'b1' => 0,
                'b2' => 0,
                'b3' => 0,
            ];

            db('sign')->where(['order_id' => $data['order_id'], 'user_id' => $this->us['user_id']])->update($sign);
        } else {

            if ($op) {
                $hello    = explode('-', $op['contract'])[1];
                $contract = $this->us['number'] . '-' . ((int)$hello + 1);
            } else {
                $contract = $this->us['number'] . '-1';
            }
            $sign = [
                'idnumber' => $data['idnumber'],
                'contract' => $contract,
                'username' => $data['username'],
                'order_id' => $data['order_id'],
                'user_id' => $this->us['user_id'],
                'addtime' => strtotime($data['addtime']),
                'uptime' => strtotime($data['uptime']),
                'addres' => $data['addres'],
                'ding' => 0,
                'zhong' => 0,
                'wei' => 0,
                'b1' => 0,
                'b2' => 0,
                'b3' => 0,
            ];

            db('sign')->insertGetId($sign);
        }

        r_date($op, 200);
    }

    /**
     * 电子报价显示
     */
    public function xian()
    {
        $data           = Request::instance()->post();
        $order          = db('order')->where('order_id', $data['order_id'])->field('contacts,ification')->find();
        $op             = db('sign')->where(['order_id' => $data['order_id'], 'user_id' => $this->us['user_id']])->field('username,idnumber,contract,addtime,uptime,addres')->find();
        $op['username'] = $order['contacts'];
        $op['idnumber'] = !empty($op['idnumber']) ? $op['idnumber'] : null;
        $op['contract'] = !empty($op['contract']) ? $op['contract'] : null;
        $op['addtime']  = !empty($op['addtime']) ? date('Y-m-d H:i', $op['addtime']) : null;
        $op['uptime']   = !empty($op['uptime']) ? date('Y-m-d H:i', $op['uptime']) : null;
        $op['addres']   = !empty($op['addres']) ? $op['addres'] : null;
        $thro           = db('through')->where(['order_ids' => $data['order_id'], 'baocun' => 1])->order('th_time desc')->find();
        if ($thro['baocun'] == 1) {
            $list = 1;
        } else {
            $list = 2;
        }
        if ($order['ification'] == 2) {
            $capital   = db('capital')->where(['ordesr_id' => $data['order_id'], 'enable' => 1, 'types' => 1])->field('projectId,capital_id,class_a,class_b,company,square,un_Price,zhi,to_price,fen')->select();
            $envelopes = db('envelopes')->where('ordesr_id', $data['order_id'])->find();
            if ($envelopes['give_b']) {
                $envelopes['give_b'] = explode(',', $envelopes['give_b']);
            } else {
                $envelopes['give_b'] = null;
            }
            if ($envelopes['capitalgo']) {
                $envelopes['capitalgo'] = unserialize($envelopes['capitalgo']);
            } else {
                $envelopes['capitalgo'] = null;
            }
            $envelopes['yc'] = $list;
            $op              = [
                'user' => $op,
                'gong' => $envelopes,
                'company' => $capital,
            ];
        } else {
            $capital = db('capital')->where(['ordesr_id' => $data['order_id'], 'enable' => 1, 'types' => 1])->field('projectId,capital_id,class_a,class_b,company,square,un_Price,zhi,to_price,give_money,gong,capitalgo,fen')->select();
            foreach ($capital as $k => $l) {
                if ($l['give_money'] != 0) {
                    $envelopes['give_money'] = $l['give_money'];
                }
                $envelopes['gong'] = !empty($l['gong']) ? $l['gong'] : 0;

                if ($l['capitalgo']) {
                    $envelopes['capitalgo'] = unserialize($l['capitalgo']);
                }
                $envelopes['yc']        = $list;
                $capi[$k]['class_a']    = !empty($l['class_a']) ? $l['class_a'] : null;
                $capi[$k]['class_b']    = !empty($l['class_b']) ? $l['class_b'] : null;
                $capi[$k]['company']    = !empty($l['company']) ? $l['company'] : null;
                $capi[$k]['square']     = !empty($l['square']) ? $l['square'] : null;
                $capi[$k]['un_Price']   = !empty($l['un_Price']) ? $l['un_Price'] : null;
                $capi[$k]['zhi']        = $l['zhi'];
                $capi[$k]['to_price']   = !empty($l['to_price']) ? $l['to_price'] : null;
                $capi[$k]['capital_id'] = !empty($l['capital_id']) ? $l['capital_id'] : null;
                $capi[$k]['fen']        = !empty($l['fen']) ? $l['fen'] : null;
                $capi[$k]['projectId']  = $l['projectId'];
                unset($capital[$k]);

            }
            $op = [
                'user' => $op,
                'gong' => !empty($envelopes) ? $envelopes : null,
                'company' => $capi,

            ];

        }

        r_date($op, 200);
    }

    /**
     * 基检
     */
    public function add_jian()
    {
        $data = Request::instance()->post();
        db()->startTrans();
        try {
            if ($data['company']) {
                $op = json_decode($data['company']);
                $op = $this->object2array($op);
                foreach ($op as $ke => $v) {
                    if ($v['types'] == 0) {
                        $product_chan = db('product_chan')->where('product_id', $v['product_id'])->find();
                        $users        = [
                            'wen_a' => '',
                            'wen_b' => '',
                            'wen_c' => '',
                            'company' => $v['unit'],//单位
                            'square' => $v['fang'],//方量
                            'un_Price' => $product_chan['prices'],//单价
                            'rule' => $product_chan['price_rules'],//规则
                            'zhi' => $v['zhi'],//质保
                            'types' => 1,//状态
                            'fen' => 0,//状态
                            'to_price' => $product_chan['prices'] * $v['fang'],//总价
                            'crtime' => time(),
                            'ordesr_id' => $data['order_id'],
                            'class_a' => $v['title'],//三
                            'class_b' => $v['projectTitle'],//三
                            'enable' => 1,//三
                            'programme' => 1,//三
                            'projectId' => $v['product_id'],//三
                        ];
                    } elseif ($v['types'] == 1) {
                        $product_chan = db('detailed')->where('detailed_id', $v['product_id'])->find();
                        $users        = [
                            'wen_a' => '',
                            'wen_b' => '',
                            'wen_c' => '',
                            'company' => $v['unit'],//单位
                            'square' => $v['fang'],//方量
                            'un_Price' => $product_chan['artificial'],//单价
                            'rule' => $product_chan['rmakes'],//规则
                            'zhi' => $v['zhi'],//质保
                            'types' => 1,//状态
                            'fen' => 1,//状态
                            'to_price' => $product_chan['artificial'] * $v['fang'],//总价
                            'crtime' => time(),
                            'ordesr_id' => $data['order_id'],
                            'class_a' => $v['title'],//三
                            'class_b' => $v['projectTitle'],//三
                            'qi_rmakes' => '',
                            'enable' => 1,//三
                            'programme' => 1,//三
                            'projectId' => $v['product_id'],//三
                        ];

                    } elseif ($v['types'] == 2) {
                        $users = [
                            'wen_a' => '',
                            'wen_b' => '',
                            'wen_c' => '',
                            'company' => $v['unit'],//单位
                            'square' => $v['fang'],//方量
                            'un_Price' => $v['prices'],//单价
                            'ordesr_id' => $data['order_id'],
                            'rule' => '',//规则
                            'zhi' => $v['zhi'],//质保
                            'types' => 1,//状态
                            'fen' => 2,//状态
                            'to_price' => $v['fang'] * $v['prices'],//总价
                            'crtime' => time(),
                            'class_a' => $v['title'],//三
                            'class_b' => $v['projectTitle'],//三
                            'qi_rmakes' => '',
                            'enable' => 1,//三
                            'programme' => 1,//三
                        ];

                    }

                    db('capital')->insertGetId($users);
                }
            }
            db('envelopes')->insertGetId([
                'wen_a' => $data['wen_a'],//一级分类
                'give_b' => !empty($data['give_a']) ? substr($data['give_a'], 0, -1) : '',
                'ordesr_id' => $data['order_id'],
                'gong' => $data['gong'],
                'give_remarks' => $data['give_remarks'],//备注
                'give_money' => $data['give_money'],//优惠金额
                'capitalgo' => !empty($data['capitalgo']) ? serialize(json_decode($data['capitalgo'], true)) : '',

            ]);

            vendor('foxyzeng.huyi.HuYiSMS');
            $sms     = new HuYiSMS();
            $us      = db('order')->where('order_id', $data['order_id'])->value('telephone');
            if(preg_match("/^1[345678]{1}\d{9}$/",$us)){
                $content = "亲，益鸟工程师已经为您完成上门基检，您是否还满意呢？如果对报价和方案有任何疑问题，都可致电：4000987009，回T退订【益鸟维修】";
                $sms->duan($us, $content);
            }

            $cap = db('order')->where(['order_id' => $data['order_id']])->field('ification,planned,appointment')->find();
            $pdf = $this->pdf->put($data['order_id'], 2,$cap);
            db('user')->where('user_id', $this->us['user_id'])->update(['lat' => $data['lat'], 'lng' => $data['lng']]);
            //页面停留时长
            db('stay')->insertGetId(['startTime' =>  substr($data['startTime'],0,-3), 'endTime' => substr($data['endTime'],0,-3),'user_id'=>$this->us['user_id'],'order_id'=>$data['order_id'],'time'=>time()]);

            //报价及时性
            db('quote')->insertGetId(['startTime' => $cap['appointment'], 'planned' => $cap['planned'],'user_id'=>$this->us['user_id'],'order_id'=>$data['order_id'],'time'=>time()]);
            if ($pdf) {
                db()->commit();
                r_date(null, 200);
            }

        } catch (Exception $e) {
            db()->rollback();
            r_date(null, 300, $e->getMessage());
        }


    }

    /**
     * 基建自定义历史列表
     *
     */
    public function information()
    {
        $data = Request::instance()->post();
        if ($data['type'] == 1) {
            $object = db('information')->where(['types' => 1, 'user_id' => $this->us['user_id']])->field('id,class_a,class_b,company,square,un_Price,zhi,fen,qi_rmakes')->select();
            foreach ($object as $k => $l) {
                $pr[$k]['projectId']    = $l['id'];
                $pr[$k]['projectMoney'] = $l['un_Price'];
                $pr[$k]['projectTitle'] = $l['class_b'];
                $pr[$k]['title']        = $l['company'];
                $pr[$k]['tao']          = $l['fen'];
                unset($object[$k]);
            }
            $pr = !empty($pr) ? $pr : null;
        } else {
            $object = db('information')->where(['id' => $data['id'], 'types' => 1, 'user_id' => $this->us['user_id']])->field('id,class_a,class_b,company,square,un_Price,zhi,fen,qi_rmakes')->find();

            $pr['projectId']    = $object['id'];
            $pr['projectMoney'] = $object['un_Price'];
            $pr['projectTitle'] = $object['class_b'];
            $pr['title']        = $object['company'];
            $pr['tao']          = $object['fen'];


        }

        r_date($pr, 200);
    }

    /*
     *
     * 增加自定义历史记录
     */
    public function inf_add()
    {

        $data = Request::instance()->post();

        db('information')->insertGetId([
            'company' => $data['unit'],//单位
            'square' => $data['fang'],//方量
            'un_Price' => $data['projectMoney'],//单价
            'zhi' => $data['zhi'],//质保
            'types' => 1,//状态
            'fen' => 3,//状态
            'to_price' => $data['fang'] * $data['projectMoney'],//总价
            'crtime' => time(),
            'user_id' => $this->us['user_id'],
            'class_a' => $data['title'],//三
            'class_b' => $data['projectTitle'],//三
            'qi_rmakes' => $data['qi_rmakes'],
        ]);

        r_date([], 200);
    }

    /*
     *
     * 删除自定义历史记录
     */
    public function inf_dell()
    {

        $data = $this->model->post(['id']);

        $p = db('information')->where('id', $data['id'])->update(['types' => 2]);
        if ($p) {
            r_date([], 200);
        }
        r_date([], 300);
    }

    /**
     * 远程沟通外面
     */
    public function gou()
    {
        $data = Request::instance()->post();
        db()->startTrans();
        try {
            if (!empty($data['capital_id'])) {
                db('capital')->where(['capital_id' => ['in', $data['capital_id']]])->delete();
            }

            $cap = '';
            if ($data['company']) {
                $op = json_decode($data['company']);
                $op = $this->object2array($op);
                foreach ($op as $ke => $v) {
                    if ($v['types'] == 0) {
                        $product_chan = db('product_chan')->where('product_id', $v['product_id'])->find();
                        $users        = [
                            'wen_a' => '',//一级分类
                            'wen_b' => '',//二
                            'wen_c' => '',//三
                            'company' => $v['unit'],//单位
                            'square' => $v['fang'],//方量
                            'un_Price' => $product_chan['prices'],//单价
                            'rule' => $product_chan['price_rules'],//规则
                            'zhi' => $v['zhi'],//质保
                            'types' => 1,//状态
                            'fen' => 0,//状态
                            'to_price' => $product_chan['prices'] * $v['fang'],//总价
                            'capitalgo' => '',//优惠金额
                            'crtime' => time(),
                            'ordesr_id' => $data['order_id'],
                            'give_a' => '',//赠送项目
                            'give_b' => '',
                            'gong' => '',
                            'give_remarks' => '',//备注
                            'give_money' => '',//优惠金额
                            'class_a' => $v['title'],//三
                            'class_b' => $v['projectTitle'],//三
                            'qi_rmakes' => '',
                            'enable' => $data['baocun'],//三
                            'programme' => 3,//三
                            'projectId' => $v['product_id'],//三
                        ];
                    } elseif ($v['types'] == 1) {
                        $product_chan = db('detailed')->where('detailed_id', $v['product_id'])->find();
                        $users        = [
                            'wen_a' => '',//一级分类
                            'wen_b' => '',//二
                            'wen_c' => '',//三
                            'company' => $v['unit'],//单位
                            'square' => $v['fang'],//方量
                            'un_Price' => $product_chan['artificial'],//单价
                            'rule' => $product_chan['rmakes'],//规则
                            'zhi' => $v['zhi'],//质保
                            'types' => 1,//状态
                            'fen' => 1,//状态
                            'to_price' => $product_chan['artificial'] * $v['fang'],//总价
                            'capitalgo' => '',//优惠金额
                            'crtime' => time(),
                            'ordesr_id' => $data['order_id'],
                            'give_a' => '',//赠送项目
                            'give_b' => '',
                            'gong' => '',
                            'give_remarks' => '',//备注
                            'give_money' => '',//优惠金额
                            'class_a' => $v['title'],//三
                            'class_b' => $v['projectTitle'],//三
                            'qi_rmakes' => '',
                            'enable' => $data['baocun'],//三
                            'programme' => 3,//三
                            'projectId' => $v['product_id'],//三
                        ];
                    } elseif ($v['types'] == 2) {
                        $users = [
                            'wen_a' => '',//一级分类
                            'wen_b' => '',//二
                            'wen_c' => '',//三
                            'company' => $v['unit'],//单位
                            'square' => $v['fang'],//方量
                            'un_Price' => $v['prices'],//单价
                            'rule' => '',//规则
                            'zhi' => $v['zhi'],//质保
                            'types' => 1,//状态
                            'fen' => 2,//状态
                            'to_price' => $v['fang'] * $v['prices'],//总价
                            'capitalgo' => '',//优惠金额
                            'crtime' => time(),
                            'ordesr_id' => $data['order_id'],
                            'give_a' => '',//赠送项目
                            'give_b' => '',
                            'gong' => '',
                            'give_remarks' => '',//备注
                            'give_money' => '',//优惠金额
                            'class_a' => $v['title'],//三
                            'class_b' => $v['projectTitle'],//三
                            'qi_rmakes' => '',
                            'enable' => $data['baocun'],//三
                            'programme' => 3,//三

                        ];
                    }
                    $p[]     = $users['to_price'];
                    $capital = db('capital')->insertGetId($users);
                    $cap     .= $capital . ',';
                    $c       = substr($cap, 0, -1);
                }

            }


            if ($data['amount'] != 0.0) {
                $o = round(array_sum($p), 2);
                if ($o != $data['amount']) {
                    db()->rollback();
                    r_date(null, 300, '金额有误');
                }
            } else {
                $o = 0;
            }
            $t = [
                'mode' => $data['mode'],
                'amount' => $o,
                'remar' => $data['remar'],
                'order_ids' => $data['order_id'],
                'admin_id' => $this->us['user_id'],
                'baocun' => $data['baocun'],
                'th_time' => time(),
                'end_time' => strtotime($data['end_time']),
                'log' => !empty($data['log']) ? serialize(json_decode($data['log'], true)) : '',//图片
                'capital_id' => !empty($c) ? $c : '',//图片

            ];
            if (!empty($data['through_id'])) {
                $p = db('through')->where('through_id', $data['through_id'])->update($t);
            } else {
                $p = db('through')->insertGetId($t);
            }

            $d = db('through')->where('order_ids', $data['order_id'])->select();
            $s = '';
            foreach ($d as $item) {
                $s .= $item['through_id'] . ',';
            }

            $s = substr($s, 0, -1);  //利用字符串截取函数消除最后一个逗号
            if ($data['baocun'] == 1) {

                db('order')->where(['order_id' => $data['order_id'], 'assignor' => $this->us['user_id']])->update(['through_id' => $s, 'state' => 3, 'update_time' => time()]);
                remind($data['order_id'], 3);
            } elseif ($data['baocun'] == 0) {

                db('order')->where(['order_id' => $data['order_id'], 'assignor' => $this->us['user_id']])->update(['through_id' => $s, 'state' => 2, 'update_time' => time()]);

            }

            vendor('foxyzeng.huyi.HuYiSMS');
            $sms      = new HuYiSMS();
            $us       = db('order')->where('order_id', $data['order_id'])->value('telephone');
            $username = $this->us['username'];

            $content = "业主您好，我是益鸟维修店长工程师：{$username}，很荣幸为您提供一些咨询建议，您这边可以多方考虑和对比呢。感谢您选择益鸟维修，如有任何需要，都可咨询：4000987009~回T退订【益鸟维修】";
            //            $sms->duan($us,$content);

            db()->commit();
            r_date($p, 200, '新增成功');
        } catch (Exception $e) {
            db()->rollback();
            r_date([], 300, $e->getMessage());
        }


    }

    /**
     * 远程沟通删除
     */
    public function deletion()
    {
        $data = Request::instance()->post();
        db()->startTrans();
        try {
            $p = db('through')->where('through_id', $data['through_id'])->field('capital_id')->find();
            db('capital')->where(['capital_id' => ['in', $p['capital_id']]])->delete();
            db('through')->where('through_id', $data['through_id'])->delete();
            $d = db('through')->where('order_ids', $data['order_id'])->select();
            $s = '';
            foreach ($d as $item) {
                $s .= $item['through_id'] . ',';
            }
            $s = substr($s, 0, -1);  //利用字符串截取函数消除最后一个逗号
            db('order')->where(['order_id' => $data['order_id'], 'assignor' => $this->us['user_id']])->update(['through_id' => $s, 'update_time' => time()]);
            db()->commit();
            r_date($p, 200, '删除成功');
        } catch (Exception $e) {
            db()->rollback();
            r_date([], 300, $e->getMessage());
        }


    }

    /**
     * 远程沟通列表
     */
    public function gou_list()
    {
        $data = $this->model->post(['page' => 1, 'limit' => 10, 'order_ids']);
        $da   = db('through')->where(['capital_id' => ['neq', ' '], 'order_ids' => $data['order_ids']])->field('amount,remar,th_time,capital_id,mode,through_id')->page($data['page'], $data['limit'])->order('th_time desc')->select();
        foreach ($da as $k => $item) {
            $da[$k]['th_time'] = date('Y-m-d H:i:s', $item['th_time']);
//            $da[$k]['data']    = db('capital')->where(['capital_id' => ['in', $item['capital_id']], 'types' => 1])->field('class_a,class_b,company,square,un_Price,zhi,fen')->select();
            unset($da[$k]['capital_id']);
        }
        r_date($da, 200);
    }

    /**
     * 远程沟通里面
     */
    public function gou2()
    {

        $data = $this->model->post(['remar', 'order_id', 'end_time', 'mode', 'log']);

        db()->startTrans();
        try {
            $t = [
                'mode' => $data['mode'],
                'amount' => 0,
                'role' => 2,
                'admin_id' => $this->us['user_id'],
                'remar' => $data['remar'],
                'order_ids' => $data['order_id'],
                'baocun' => 0,
                'th_time' => time(),
                'end_time' => strtotime($data['end_time']),
                'log' => !empty($data['log']) ? serialize(json_decode($data['log'], true)) : '',//图片
            ];

            db('through')->insertGetId($t);

            $d = db('through')->where('order_ids', $data['order_id'])->select();
            $s = '';
            foreach ($d as $item) {
                $s .= $item['through_id'] . ',';
            }
            $s = substr($s, 0, -1);
            db('order')->where(['order_id' => $data['order_id'], 'assignor' => $this->us['user_id']])->update(['through_id' => $s]);
            //            vendor('foxyzeng.huyi.HuYiSMS');
            //            $sms=new HuYiSMS();
            //            $us=db('order')->where('order_id',$data['order_id'])->value('telephone');
            //            $content = "业主您好，我是益鸟维修店长工程师：{$user['username']}，很荣幸为您提供一些咨询建议，您这边可以多方考虑和对比呢。感谢您选择益鸟维修，如有任何需要，都可咨询：4000987009~回T退订【益鸟维修】";
            //            $sms->duan($us,$content);
            db()->commit();
            r_date([], 200, '新增成功');
        } catch (Exception $e) {
            db()->rollback();
            r_date([], 300, $e->getMessage());
        }


    }

    /**
     * 远程沟通列表
     */
    public function get_gou()
    {
        $data = $this->model->post(['order_ids', 'gid']);
        $k    = db('through');
        if ($data['gid']) {

            if (strstr("店长", $data['gid'])) {
                $k->where(['role' => [['eq', 2], ['neq', 3]]]);
            } elseif (strstr("客服", $data['gid'])) {
                $k->where(['role' => [['eq', 1], ['neq', 3]]]);
            } elseif (strstr("客户", $data['gid'])) {
                $k->where(['role' => [['eq', 4], ['neq', 3]]]);
            } else {
                $k->where(['role' => [['eq', 6], ['neq', 3]]]);
            }


        } else {
            $k->where(['role' => ['neq', 3]]);
        }
        $h = $k->where(['order_ids' => $data['order_ids']])->order('end_time asc,th_time desc')->select();

        foreach ($h as $k => $value) {
            if ($value['log']) {
                $h[$k]['log'] = unserialize($value['log']);
            } else {
                $h[$k]['log'] = null;
            }
            $h[$k]['remar']   = !empty($value['remar']) ? $value['remar'] : '';
            $h[$k]['th_time'] = !empty($value['th_time']) ? date('Y-m-d H:i:s', $value['th_time']) : null;
        }

        r_date($h, 200);
    }


    /************************************************************** 订单列表**************************************************************/


    public function get_order()
    {

        $data = $this->model->post(['state', 'page' => 1, 'limit' => 10, 'title', 'orderType', 'time_status', 'rework', 'followUp_time', 'planned','type']);
        $m    = db('order')
            ->alias('a')
            ->field('a.order_id,a.ification,a.order_no,a.addres,a.contacts,a.telephone,a.remarks,a.lat,a.lng,a.created_time,a.state,a.quotation,a.planned,b.title,p.province,c.city,u.county,go.title,co.con_time,co.dep_money,co.weixin,st.dep,st.con,st.up_time,st.sta_time,be.tail,a.label_id,order.point,cos.type')
            ->join('chanel b', 'a.channel_id=b.id', 'left')
            ->join('province p', 'a.province_id=p.province_id', 'left')
            ->join('city c', 'a.city_id=c.city_id', 'left')
            ->join('county u', 'a.county_id=u.county_id', 'left')
            ->join('goods_category go', 'a.pro_id=go.id', 'left')
            ->join('label la', 'a.label_id=la.label_id', 'left')
            ->join('contract co', 'a.contract_id=co.contract_id', 'left')
            ->join('startup st', 'a.startup_id=st.startup_id', 'left')
            ->join('before be', 'a.before_id=be.before_id', 'left')
            ->join('cost cos', 'a.order_id=cos.order_id', 'left')
            ->where(['a.assignor' => $this->us['user_id']]);
        if (isset($data['title']) && $data['title'] != '') {
            $map['a.contacts|a.telephone|a.addres|go.title'] = array('like', "%{$data['title']}%");
            $m->where($map);
        }
        if (isset($data['state']) && $data['state'] != '') {
            db('remind')->where(['admin_id' => $this->us['user_id'], 'stater' => $data['state']])->update(['tai' => 0]);
            if ($data['state'] == 2) {
                $m->where(['a.state' => $data['state']])->order('a.planned desc');
            } elseif ($data['state'] == 4) {
                $m->where(['a.state' => ['between', [4, 5]]])->order('a.update_time desc');
            } elseif ($data['state'] == 7) {
                if ($data['rework'] == 1) {
                    $m->where(['a.state' => ['between', [6, 7]], 'rework' => 1])->order('be.uptime desc');
                } else {
                    $m->where(['a.state' => ['between', [6, 7]], 'rework' => 0])->order('be.uptime desc');
                }
            } else {
                $m->where(['a.state' => $data['state']])->order('a.update_time desc');
            }
        }
        if (isset($data['type']) && $data['type'] != '' && $data['type']==2) {

            $m->where(['cos.type' =>1])->order('a.update_time desc');

        }
        if (isset($data['orderType']) && $data['orderType'] != '' && $data['orderType'] == 1) {
            $m->where(['a.through_id' => ['NEQ', 'NULL']])->order('a.update_time desc');
        };

        $list = $m->page($data['page'], $data['limit'])->select();

        foreach ($list as $k => $key) {
            $label                    = db('label')->where('label_id', 'in', $key['label_id'])->select();
            $list[$k]['label_name']   = $label;
            $list[$k]['con_time']     = !empty($key['con_time']) ? date('Y-m-d H:i:s', $key['con_time']) : '';
            $list[$k]['up_time']      = !empty($key['up_time']) ? date('Y-m-d H:i:s', $key['up_time']) : '';
            $list[$k]['sta_time']     = !empty($key['sta_time']) ? date('Y-m-d H:i:s', $key['sta_time']) : '';
            $list[$k]['created_time'] = !empty($key['created_time']) ? date('Y-m-d H:i:s', $key['created_time']) : '';
            $list[$k]['planned']      = !empty($key['planned']) ? date('Y-m-d H:i:s', $key['planned']) : '';
            $list[$k]['yu']           = 0;
            $thro                     = db('through')->where(['order_ids' => $key['order_id'], 'baocun' => 1])->order('th_time desc')->find();
            if ($thro['baocun'] == 1) {
                $list[$k]['amount'] = $thro['amount'];
                $list[$k]['yc']     = 1;
            } else {
                if ($key['ification'] == 2) {
                    $cap                = db('capital')->where(['ordesr_id' => $key['order_id'], 'types' => 1, 'enable' => 1])->sum('to_price');
                    $ca                 = db('envelopes')->where(['ordesr_id' => $key['order_id']])->field('give_money')->find();
                    $list[$k]['amount'] = $cap - $ca['give_money'];
                } else {
                    $ca                 = db('capital')->where(['ordesr_id' => $key['order_id'], 'types' => 1, 'enable' => 1])->field('sum(to_price),sum(give_money)')->find();
                    $list[$k]['amount'] = $ca['sum(to_price)'] - $ca['sum(give_money)'];
                }
                $list[$k]['yc'] = 2;

            }
            $list[$k]['yu'] = $list[$k]['amount'] - $key['dep_money'] - $key['dep'] - $key['tail'];
            $cash   = 0;
            $WeChat = 0;
            if ($list[$k]['yu'] > 0) {
                $pa = db('payment')->where(['orders_id' => $key['order_id']])->select();
                foreach ($pa as $kl) {
                    if ($kl['weixin'] == 1) {
                        $cash += $kl['money'];
                    }
                    if ($kl['success'] == 2 && $kl['weixin'] == 2) {
                        $WeChat += $kl['money'];
                    }
                }
                if (!empty($cash)) {
                    $list[$k]['yu'] = $list[$k]['yu'] - $cash;
                    $list[$k]['yu'] = round($list[$k]['yu'], 3);
                }
                if (!empty($WeChat)) {
                    $list[$k]['yu'] = $list[$k]['yu'] - $WeChat;
                    $list[$k]['yu'] = round($list[$k]['yu'], 3);
                }
            }
            $i                    = db('through')->where(['order_ids' => $key['order_id'], 'role' => 2])->field('end_time')->order('through_id desc')->find();
            $list[$k]['end_time'] = !empty($i['end_time']) ? date('Y-m-d H:i:s', $i['end_time']) : '';
            if (isset($data['followUp_time']) && $data['followUp_time'] != '') {
                if ($data['followUp_time'] == 1) {
                    $current_time = time();
                    if ($data['followUp_time'] == 1) {
                        $starttime = 3 * 24 * 3600;
                    }
                    $span = $current_time - $i['end_time'];
                    if (!empty($i['end_time'])) {
                        if (abs($span) < $starttime) {
                            $list[$k]['day'] = intval($span / (24 * 3600));
                        } else {
                            unset($list[$k]);
                        }
                    } else {
                        unset($list[$k]);
                    }
                }
            }
            /*
             * 订单创建时间
            */
            if (isset($data['time_status']) && $data['time_status'] != '') {
                $current_time = time();
                if ($data['time_status'] == 1) {
                    $starttime = 3 * 24 * 3600;
                } elseif ($data['time_status'] == 2) {
                    $starttime = 7 * 24 * 3600;
                } else {
                    //一个月内的时间
                    $month     = date('m', time());
                    $year      = date('Y', time());
                    $nextMonth = (($month + 1) > 12) ? 1 : ($month + 1);
                    $year      = ($nextMonth > 12) ? ($year + 1) : $year;
                    $days      = date('d', mktime(0, 0, 0, $nextMonth, 0, $year));
                    $starttime = $days * 24 * 3600;
                }
                $span = $current_time - $key['created_time'];
                if (abs($span) < $starttime) {
                    $list[$k]['day'] = intval($span / (24 * 3600));
                } else {
                    unset($list[$k]);
                }
            }
            if (isset($data['planned']) && $data['planned'] != '') {
                $current_time = time();
                if ($data['planned'] == 1) {
                    $starttime = 3 * 24 * 3600;
                }
                $span = $current_time - $key['planned'];
                if (abs($span) < $starttime) {
                    $list[$k]['day'] = intval($span / (24 * 3600));
                } else {
                    unset($list[$k]);
                }
            }
            if (empty($data['state'])) {
            if (!empty($i)) {
                    if (isset($data['orderType']) && $data['orderType'] != '' &&$data['orderType'] == 2 ) {
                        unset($list[$k]);
                    }
                }
            }


        }

        r_date(array_merge($list));
    }


    /**
     * 订单详情
     */

    public function get_info()
    {

        $data = $this->model->post(['order_id']);
        $res  = db('order')
            ->field('order.order_id,order.ification,order.logo,order.order_no,order.lat,order.lng,order.addres,order.contacts,order.telephone,order.remarks,order.created_time,order.state,order.quotation,order.planned,b.title,p.province,c.city,y.county,go.title,co.con_time,co.type,co.contract,co.deposit,co.dep_money,st.invoice,st.sta_time,st.dep,st.con,st.up_time,st.sta_time,be.logos,be.tail,ac.full,order.label_id,order.point')
            ->join('chanel b', 'order.channel_id=b.id', 'left')
            ->join('goods_category go', 'order.pro_id=go.id', 'left')
            ->join('user u', 'order.assignor=u.user_id ', 'left')
            ->join('province p', 'order.province_id=p.province_id', 'left')
            ->join('city c', 'order.city_id=c.city_id', 'left')
            ->join('county y', 'order.county_id=y.county_id', 'left')
            ->join('contract co', 'order.contract_id=co.contract_id', 'left')
            ->join('startup st', 'order.startup_id=st.startup_id', 'left')
            ->join('product ac', 'order.product_id=ac.product_id', 'left')
            ->join('before be', 'order.before_id=be.before_id', 'left')
            ->where(['order.order_id' => $data['order_id'], 'order.assignor' => $this->us['user_id']])
            ->find();
        if ($res) {
            $res['planned'] = !empty($res['planned']) ? date('Y-m-d H:i', $res['planned']) : null;
            if (!empty($res['logo'])) {
                $res['logo'] = unserialize($res['logo']);
            } else {
                $res['logo'] = null;
            }
            if ($res['contract']) {
                $res['contract'] = unserialize($res['contract']);
            } else {
                $res['contract'] = null;
            }
            if ($res['deposit']) {
                $res['deposit'] = unserialize($res['deposit']);
            } else {
                $res['deposit'] = null;
            }
            $res['sta_time']     = !empty($res['sta_time']) ? date('Y-m-d H:i', $res['sta_time']) : null;
            $res['inside']       = !empty($res['inside']) ? $res['inside'] : null;
            $res['up_time']      = !empty($res['up_time']) ? date('Y-m-d H:i', $res['up_time']) : null;
            $res['tui_time']     = !empty($res['tui_time']) ? date('Y-m-d H:i', $res['tui_time']) : null;
            $res['con_time']     = !empty($res['con_time']) ? date('Y-m-d H:i', $res['con_time']) : null;
            $res['created_time'] = !empty($res['created_time']) ? date('Y-m-d H:i', $res['created_time']) : null;
            $res['uptime']       = !empty($res['uptime']) ? date('Y-m-d H:i', $res['uptime']) : null;
            $res['label_name']   = db('label')->where('label_id', 'in', $res['label_id'])->select();
            $res['yu']           = 0;
            $i                   = db('through')->where(['order_ids' => $data['order_id'], 'role' => 2])->field('end_time')->order('through_id desc')->find();
            $res['end_time']     = !empty($i['end_time']) ? date('Y-m-d H:i:s', $i['end_time']) : null;
            //签约金额
            $thro = db('through')->where(['order_ids' => $data['order_id'], 'baocun' => 1])->field('amount')->order('th_time desc')->find();
            if ($thro) {
                $res['p']  = $thro['amount'];
                $res['yc'] = 1;
            } else {
                if ($res['ification'] == 2) {
                    $cap      = db('capital')->where(['ordesr_id' => $data['order_id'], 'types' => 1, 'enable' => 1])->sum('to_price');
                    $ca       = db('envelopes')->where(['ordesr_id' => $data['order_id']])->field('give_money')->find();
                    $res['p'] = $cap - $ca['give_money'];
                } else {
                    $ca       = db('capital')->where(['ordesr_id' => $data['order_id'], 'types' => 1, 'enable' => 1])->field('sum(to_price),sum(give_money)')->find();
                    $res['p'] = $ca['sum(to_price)'] - $ca['sum(give_money)'];
                }
                $res['yc'] = 2;
            }
            $res['payment']     = 1;
            $res['system_time'] = time();
            if (!empty($res['dep_money']) && $res['dep_money'] != 0.00) {
                $res['yu'] = $res['p'] - $res['dep_money'];
            }
            $res['yu']        = $res['p'] - $res['dep_money'] - $res['dep'] - $res['tail'];
            $res['dep_money'] = $res['dep_money'] + $res['dep'] + $res['tail'];
            $cash             = 0;
            $WeChat           = 0;

            if ($res['yu'] > 0) {
                $pa = db('payment')->where(['orders_id' => $res['order_id']])->select();
                foreach ($pa as $kl) {
                    if ($kl['weixin'] == 1) {
                        $cash += $kl['money'];
                    }
                    if ($kl['success'] == 2 && $kl['weixin'] == 2) {
                        $WeChat += $kl['money'];
                    }
                }

                if (!empty($cash)) {
                    $res['yu'] = $res['yu'] - $cash;
                    $res['yu'] = round($res['yu'], 3);

                }

                if (!empty($WeChat)) {
                    $res['yu'] = $res['yu'] - $WeChat;
                    $res['yu'] = round($res['yu'], 3);

                }

            }
            $pa = db('payment')->where(['orders_id' => $res['order_id']])->order('payment_id desc')->field('money,weixin')->find();
            if ($pa) {
                $res['dep_money'] = $pa['money'];
                if ($pa['weixin'] == 2) {
                    $payment = db('recharge')->where(['order_no' => $res['order_no'], 'status' => 1, 'type' => 2, 'money' => $pa['money']])->find();
                    if (!$payment) {
                        $res['payment'] = 2;
                    }
                }
            }
        } else {
            $res = null;
        }
        $message=db('message')->where(['order_id' => $data['order_id'], 'user_id' => $this->us['user_id']])->order('id desc')->find();


           if($message['already'] !=0){

               db('message')->where(['order_id' => $data['order_id'], 'user_id' => $this->us['user_id']])->update(['already' => 0,'have'=>time()]);
           }

        r_date($res);
    }

    /*
     * 沟通记录详情
     *
     */
    public function get_quote()
    {

        $data = $this->model->post(['order_id', 'through_id']);
        $res  = db('order')
            ->field('order.order_id,order.logo,order.order_no,order.addres,order.contacts,order.telephone,order.remarks,p.province,c.city,y.county,go.title')
            ->join('goods_category go', 'order.pro_id=go.id', 'left')
            ->join('user u', 'order.assignor=u.user_id ', 'left')
            ->join('province p', 'order.province_id=p.province_id', 'left')
            ->join('city c', 'order.city_id=c.city_id', 'left')
            ->join('county y', 'order.county_id=y.county_id', 'left')
            ->where(['order.order_id' => $data['order_id'], 'order.assignor' => $this->us['user_id']])
            ->find();

        if ($res) {
            if ($res['logo']) {
                $res['logo'] = unserialize($res['logo']);
                if (empty($res['logo'])) {
                    $res['logo'] = null;
                }
            } else {

                $res['logo'] = null;
            }
            $res['remarks'] = !empty($res['remarks']) ? $res['remarks'] : '';
            if (!empty($data['through_id'])) {
                $res['gou'] = db('through')->where(['through_id' => $data['through_id']])->field('amount,remar,mode,th_time,log,end_time,capital_id')->order('th_time desc')->find();
            } else {
                $res['gou'] = db('through')->where(['order_ids' => $data['order_id']])->field('amount,remar,mode,th_time,log,end_time,capital_id')->order('th_time desc')->find();
            }

            if (!empty($res['gou'])) {
                $res['gou']['remar'] = !empty($res['gou']['remar']) ? $res['gou']['remar'] : '';
                if ($res['gou']['capital_id']) {

                    $res['gou']['company'] = db('capital')->where(['capital_id' => ['in', $res['gou']['capital_id']], 'types' => 1])->field('class_a,class_b,company,square,un_Price,zhi,fen,capital_id')->order('capital_id desc')->select();
                    foreach ($res['gou']['company'] as $k => $m) {
                        if ($m['fen'] == 0) {
                            $pro                                   = db('product_chan')->where(['product_title' => $m['class_b']])->field('product_id')->find();
                            $res['gou']['company'][$k]['detailed'] = $pro['product_id'];
                        } elseif ($m['fen'] == 1) {
                            $pro                                   = db('detailed')->where(['detailed_title' => $m['class_b']])->field('detailed_id')->find();
                            $res['gou']['company'][$k]['detailed'] = $pro['detailed_id'];
                        } else {
                            $pro                                   = db('information')->where(['class_b' => $m['class_b'], 'types' => 1, 'user_id' => $this->us['user_id'], 'un_Price' => $m['un_Price']])->field('id')->find();
                            $res['gou']['company'][$k]['detailed'] = $pro['id'];
                        }

                    }
                }
                if ($res['gou']['log']) {
                    $res['gou']['log'] = unserialize($res['gou']['log']);
                } else {
                    $res['gou']['log'] = null;
                }
                $res['gou']['th_time']  = !empty($res['gou']['th_time']) ? date("Y-m-d H:i", $res['gou']['th_time']) : '';
                $res['gou']['end_time'] = !empty($res['gou']['end_time']) ? date("Y-m-d H:i", $res['gou']['end_time']) : '';

            } else {
                $res['gou'] = null;
            }

        } else {
            $res = '';
        }


        r_date($res);
    }

    /**
     * 报价信息
     */
    public function get_jia()
    {
        $data = $this->model->post(['order_id']);
        $s    = db('capital')->where(['ordesr_id' => $data['order_id'], 'types' => 1, 'enable' => 1])->select();

        foreach ($s as $o => $y) {
            if ($y['capitalgo']) {
                $s[$o]['capitalgo'] = unserialize($y['capitalgo']);
            }
            $s1 = db('order')->where(['order_id' => $data['order_id']])->value('state');

            if ($s1 < 4) {
                $o8 = db('capital')->where(['ordesr_id' => $data['order_id'], 'types' => 1, 'programme' => 2])->select();
                if ($o8) {
                    $s[$o]['sisi'] = 1;
                } else {
                    $s[$o]['sisi'] = 0;
                }
            } else {
                $s[$o]['sisi'] = 0;
            }

        }
        $sign = db('sign')->where(['order_id' => $data['order_id']])->find();
        $o    = [
            0 => $s,
            1 => empty($sign) ? '' : $sign,
        ];
        r_date($o, 200);
    }

    /**
     * 远程报价详情
     */
    public function get_yc()
    {
        $data = $this->model->post(['order_id']);
        $s    = db('capital')->where(['ordesr_id' => $data['order_id'], 'types' => 1, 'enable' => 1])->select();
        $da   = [
            0 => $s
        ];

        r_date($da, 200);
    }

    /**
     * 是否报价了
     */
    public function get_cha()
    {
        $data = $this->model->post(['order_id']);
        $s    = db('through')->where(['order_ids' => $data['order_id'], 'baocun' => 1])->find();
        if ($s) {
            r_date([], 300);
        } else {
            r_date([], 200);
        }


    }

    /*********************************************************************** * 重点标签***************************************************************************  */
    public function get_biao()
    {
        $data = $this->model->post(['page' => 1, 'limit' => 10, 'label_id', 'title', 'time_status']);
        $m    = db('order')
            ->alias('a')
            ->field('a.*,b.title,p.province,c.city,u.county,go.title,co.con_time,co.weixin,co.dep_money,st.dep,st.con,st.up_time,st.sta_time,be.tail')
            ->join('chanel b', 'a.channel_id=b.id', 'left')
            ->join('province p', 'a.province_id=p.province_id', 'left')
            ->join('city c', 'a.city_id=c.city_id', 'left')
            ->join('county u', 'a.county_id=u.county_id', 'left')
            ->join('goods_category go', 'a.pro_id=go.id', 'left')
            ->join('label la', 'a.label_id=la.label_id', 'left')
            ->join('contract co', 'a.contract_id=co.contract_id', 'left')
            ->join('startup st', 'a.startup_id=st.startup_id', 'left')
            ->join('before be', 'a.before_id=be.before_id', 'left')
            ->where(['a.assignor' => $this->us['user_id'], 'a.state' => ['<>', 0]]);
        if (isset($data['title']) && $data['title'] != '') {
//            $li = db('goods_category')->where(['title' => ['like', "%{$data['title']}%"]])->field('id')->select();
//
//            $s  = '';
//            foreach ($li as $key => $val) {
//                $s .= $val["id"] . ',';
//            }
//            $s = substr($s, 0, -1);
            $map['a.contacts|a.telephone|a.addres|go.title'] = array('like', "%{$data['title']}%");
//            $map['contacts|telephone|addres|'] = array('like', "%{$data['title']}%");
//            if (!empty($s)) {
//
//                $m->where(['a.pro_id' => ['in',$s]]);
//            }
            $m->where($map);


        }

        if (isset($data['label_id']) && $data['label_id'] != '') {
            $id = substr($data['label_id'], 0, -1);
            $m->where(['a.label_id' => ['like', "%{$id}%"]]);

        }

        $map2 = array('a.label_id' => ['neq', ' '], 'a.point' => 2);
        $m->where(function ($q) use ($map2) {
            $q->whereOr($map2);
        });


        $list = $m->order('a.created_time desc')->page($data['page'], $data['limit'])->select();

        foreach ($list as $k => $key) {
            $label                    = db('label')->where('label_id', 'in', $key['label_id'])->select();
            $list[$k]['label_name']   = $label;
            $list[$k]['created_time'] = !empty($key['created_time']) ? date('Y-m-d H:i:s', $key['created_time']) : '';
            $list[$k]['con_time']     = !empty($key['con_time']) ? date('Y-m-d H:i:s', $key['con_time']) : '';
            $list[$k]['planned']      = !empty($key['planned']) ? date('Y-m-d H:i:s', $key['planned']) : '';
            $list[$k]['up_time']      = !empty($key['up_time']) ? date('Y-m-d H:i:s', $key['up_time']) : '';
            $list[$k]['sta_time']     = !empty($key['sta_time']) ? date('Y-m-d H:i:s', $key['sta_time']) : '';
            $list[$k]['yu']           = 0;
            $thro                     = db('through')->where(['order_ids' => $key['order_id'], 'baocun' => 1])->order('th_time desc')->find();

            if ($thro['baocun']) {
                $list[$k]['amount'] = $thro['amount'];
                $list[$k]['yc']     = 1;
            } else {
                if ($key['ification'] == 2) {
                    $cap                = db('capital')->where(['ordesr_id' => $key['order_id'], 'types' => 1, 'enable' => 1])->sum('to_price');
                    $ca                 = db('envelopes')->where(['ordesr_id' => $key['order_id']])->field('give_money')->find();
                    $list[$k]['amount'] = $cap - $ca['give_money'];
                } else {
                    $ca                 = db('capital')->where(['ordesr_id' => $key['order_id'], 'types' => 1, 'enable' => 1])->field('sum(to_price),sum(give_money)')->find();
                    $list[$k]['amount'] = $ca['sum(to_price)'] - $ca['sum(give_money)'];
                }
                $list[$k]['yc'] = 2;

            }
            $thro = db('through')->where(['order_ids' => $key['order_id'], 'baocun' => 1])->order('th_time desc')->find();
            if ($thro['baocun'] == 1) {
                $list[$k]['amount'] = $thro['amount'];
                $list[$k]['yc']     = 1;
            } else {
                if ($key['ification'] == 2) {
                    $cap                = db('capital')->where(['ordesr_id' => $key['order_id'], 'types' => 1, 'enable' => 1])->sum('to_price');
                    $ca                 = db('envelopes')->where(['ordesr_id' => $key['order_id']])->field('give_money')->find();
                    $list[$k]['amount'] = $cap - $ca['give_money'];
                } else {
                    $ca                 = db('capital')->where(['ordesr_id' => $key['order_id'], 'types' => 1, 'enable' => 1])->field('sum(to_price),sum(give_money)')->find();
                    $list[$k]['amount'] = $ca['sum(to_price)'] - $ca['sum(give_money)'];
                }
                $list[$k]['yc'] = 2;
            }
            $list[$k]['yu'] = $list[$k]['amount'] - $key['dep_money'] - $key['dep'] - $key['tail'];
            $cash           = 0;
            $WeChat         = 0;
            if ($list[$k]['yu'] > 0) {
                $pa = db('payment')->where(['orders_id' => $key['order_id']])->select();
                foreach ($pa as $kl) {
                    if ($kl['weixin'] == 1) {
                        $cash += $kl['money'];
                    }
                    if ($kl['success'] == 2 && $kl['weixin'] == 2) {
                        $WeChat += $kl['money'];
                    }
                }
                if (!empty($cash)) {
                    $list[$k]['yu'] = $list[$k]['yu'] - $cash;
                }
                if (!empty($WeChat)) {
                    $list[$k]['yu'] = $list[$k]['yu'] - $WeChat;
                }
            }
            $i                    = db('through')->where(['order_ids' => $key['order_id'], 'role' => 2])->field('end_time')->order('through_id desc')->find();
            $list[$k]['end_time'] = !empty($i['end_time']) ? date('Y-m-d H:i:s', $i['end_time']) : '';
            /*
            * 订单创建时间
           */
            if (isset($data['time_status']) && $data['time_status'] != '') {
                $current_time = time();
                if ($data['time_status'] == 1) {
                    $starttime = 3 * 24 * 3600;
                } elseif ($data['time_status'] == 2) {
                    $starttime = 7 * 24 * 3600;
                } else {
                    //一个月内的时间
                    $month     = date('m', time());
                    $year      = date('Y', time());
                    $nextMonth = (($month + 1) > 12) ? 1 : ($month + 1);
                    $year      = ($nextMonth > 12) ? ($year + 1) : $year;
                    $days      = date('d', mktime(0, 0, 0, $nextMonth, 0, $year));
                    $starttime = $days * 24 * 3600;
                }

                $span = $current_time - $key['created_time'];

                if ($span < $starttime) {
                    $list[$k]['day'] = intval($span / (24 * 3600));
                } else {
                    unset($list[$k]);
                }
            }

        }

        r_date($list);
    }

    /**
     * 获取标签
     */
    public function get_label()
    {
        $res = db('label')->where(['user_id' => ['eq', 0]])->select();

        $rss = db('label')->where('user_id', $this->us['user_id'])->select();

        if ($rss) {
            $o = array_merge($res, $rss);
        } else {
            $o = $res;
        }

        r_date(array_values($o));
    }

    /**
     * 标记
     */
    public function point()
    {

        $data = $this->model->post(['type', 'order_id']);
        $b    = db('order')->where('order_id', $data['order_id'])->update(['point' => $data['type']]);
        if ($b) {
            r_date($b, 200);
        }
        r_date($b, 300);

    }

    /**
     * 添加标签
     */
    public function add_label()
    {

        $data = $this->model->post(['content']);
        $b    = db('label')->where('content', $data['content'])->find();
        if ($b) {
            r_date([], 300, '已存在');
        }
        $use = [
            'content' => $data['content'],
            'user_id' => $this->us['user_id'],
        ];
        $b   = db('label')->insertGetId($use);
        if ($b) {
            r_date($b, 200);
        }
        r_date($b, 300);

    }

    /**
     * 添加标签
     */
    public function set_label()
    {

        $data = $this->model->post(['order_id', 'label_id', 'inside']);
        $dat  = db('order')->where(['assignor' => $this->us['user_id'], 'order_id' => $data['order_id']])->update(['inside' => !empty($data['inside']) ? $data['inside'] : " ", 'label_id' => !empty($data['label_id']) ? substr($data['label_id'], 0, -1) : " "]);
        if ($dat) {
            r_date($dat, 200);
        }
        r_date([], 300);
    }

    /**
     * 删除标签
     */
    public function del_label()
    {
        $data  = $this->model->post(['label_id', 'order_id']);
        $dat   = db('order')->where(['assignor' => $this->us['user_id'], 'order_id' => $data['order_id']])->find();
        $c_arr = explode(',', $dat['label_id']);
        if (!in_array($data['label_id'], $c_arr)) {
            $b = db('label')->where(['label_id' => $data['label_id'], 'user_id' => $this->us['user_id']])->delete();
            if ($b) {
                r_date([], 200);
            }
        }

        r_date([], 300, '该标签已使用');

    }


    /*** ************************************************************确认时间***************************************************
     **************************************************************** types等于1是需要改变订单状态* types等于2是只需修改上门时间 */


    public function get_planned()
    {
        vendor('foxyzeng.huyi.HuYiSMS');
        $sms  = new HuYiSMS();
        $data = $this->model->post(['order_id', 'planned', 'types', 'nodian']);
        $us   = db('order')->where('order_id', $data['order_id'])->field('telephone,planned')->find();
        if ($data['types'] == 1) {
            db('order')->where(['assignor' => $this->us['user_id'], 'order_id' => $data['order_id']])->update(['planned' => strtotime($data['planned']), 'state' => 2, 'update_time' => time(),'appointment'=>time()]);
            $user    = $this->us['username'];
            $content = "业主您好，我是刚与您通话的益鸟维修店长工程师{$user}，和您约定{$data['planned']}为您上门检测，我将准时到达。如有问题，请及时联系：4000987009～回T退订【益鸟维修】";
            if(preg_match("/^1[345678]{1}\d{9}$/",$us['telephone'])){
                $sms->duan($us['telephone'], $content);
            }

            if ($data['nodian'] != 1) {
                remind($data['order_id'], 2);
            }
            $y = [
                'planneds' => '',
                'planned' => [],
            ];
        } elseif ($data['types'] == 2) {
            db('order')->where(['assignor' => $this->us['user_id'], 'order_id' => $data['order_id']])->update(['planned' => strtotime($data['planned']), 'update_time' => time(),'appointment'=>time()]);
            if (!empty($us['planned'])) {
                db('planned')->insertGetId([
                    'order_id' => $data['order_id'],
                    'planned' => $us['planned'],
                ]);
            }
            $y = [
                'planneds' => '',
                'planned' => [],
            ];

        } elseif ($data['types'] == 3) {
            $y = db('planned')->where(['order_id' => $data['order_id']])->field('planned')->order('id desc')->select();

            if (!empty($y)) {
                foreach ($y as $k => $value) {
                    $y[$k] = !empty($value['planned']) ? date("Y-m-d H:i", $value['planned']) : '';
                }
                $y = [
                    'planneds' => !empty($us['planned']) ? date("Y-m-d H:i", $us['planned']) : '',
                    'planned' => !empty($y) ? $y : [],
                ];
            } else {
                $y = [
                    'planneds' => !empty($us['planned']) ? date("Y-m-d H:i", $us['planned']) : '',
                    'planned' => [],
                ];
            }
        }
        if ($y) {
            r_date($y, 200);
        }
        r_date([], 300);
    }


    /**
     * 取消订单/退单子
     */
    public function get_reason()
    {
        $data = $this->model->post(['order_id', 'reason', 'tui_moey']);
        if (empty($data['tui_moey'])) {
            if (empty($data['reason'])) {
                r_date([], 300);
            }
            $data = db('order')->where(['assignor' => $this->us['user_id'], 'order_id' => $data['order_id']])->update(['state' => 8, 'reason' => $data['reason'], 'tui_time' => time(), 'update_time' => time()]);
        } else {
            if (empty($data['reason'])) {
                r_date([], 300);
            } elseif (empty($data['tui_moey'])) {
                r_date([], 300);
            }
            $data = db('order')->where(['order_id' => $data['order_id'], 'assignor' => $this->us['user_id']])->update(['state' => 9, 'reason' => $data['reason'], 'tui_moey' => $data['tui_moey'], 'tui_state' => 1, 'tui_time' => time(), 'update_time' => time()]);
        }

        if ($data) {
            r_date($data);
        }
        r_date([], 300);
    }

    /**
     * 签约
     */
    public function qian()
    {
        $data = $this->model->post(['contract', 'deposit', 'dep_money', 'order_id', 'type', 'weixin']);
        try {
            $kl    = [
                'contract' => !empty($data['contract']) ? serialize(json_decode($data['contract'], true)) : '',//合同
                'con_time' => time(),
                'deposit' => '',
                'orders_id' => $data['order_id'],
                'type' => $data['type'],
                'weixin' => $data['weixin'],
            ];
            $contr = db('contract')->where('orders_id', $data['order_id'])->find();
            if ($contr) {
                db('contract')->where('orders_id', $data['order_id'])->update($kl);
            } else {
                $res = db('contract')->insertGetId($kl);
            }
            db('payment')
                ->insertGetId([
                    'uptime' => time(),
                    'logos' => !empty($data['deposit']) ? serialize(json_decode($data['deposit'], true)) : '',//图片
                    'money' => $data['dep_money'],//尾款
                    'orders_id' => $data['order_id'],
                    'weixin' => $data['weixin'],
                ]);

            if ($data['type'] == 1) {
                if ($data['weixin'] == 1) {
                    if (empty($contr)) {
                        db('order')->where(['order_id' => $data['order_id'], 'assignor' => $this->us['user_id']])->update(['state' => 4, 'contract_id' => $res, 'update_time' => time()]);

                    } else {
                        db('order')->where(['order_id' => $data['order_id'], 'assignor' => $this->us['user_id']])->update(['update_time' => time(), 'state' => 4]);
                    }
                    remind($data['order_id'], 4);
                } else {
                    if (empty($contr)) {
                        db('order')->where(['order_id' => $data['order_id'], 'assignor' => $this->us['user_id']])->update(['contract_id' => $res, 'update_time' => time()]);
                    } else {
                        db('order')->where(['order_id' => $data['order_id'], 'assignor' => $this->us['user_id']])->update(['update_time' => time()]);
                    }
                }

            } else {
                if (empty($contr)) {
                    db('order')->where(['order_id' => $data['order_id'], 'assignor' => $this->us['user_id']])->update(['contract_id' => $res, 'update_time' => time()]);
                    remind($data['order_id'], 4);
                } else {
                    db('order')->where(['order_id' => $data['order_id'], 'assignor' => $this->us['user_id']])->update(['update_time' => time()]);
                }

            }
            r_date([], 200, '新增成功');
        } catch (Exception $e) {

            r_date([], 300, $e->getMessage());
        }

    }

    /*
     *
     * 开工设置
     */
    public function userlist()
    {
        $data = $this->model->post(['order_id']);
        $de   = db('startup')->where('orders_id', $data['order_id'])->field('sta_time,up_time,con,handover,xiu_id')->find();

        if ($de) {
            $shi['user'] = $de['xiu_id'];
            if (!empty($shi['user'])) {
                $results = send_post(UIP_SRC . "/shopowner/User/searchIn", $shi);
                $results = json_decode($results);
                if ($results->code == 200) {
                    $de['shi'] = object_array($results->data);
                } else {
                    $de['shi'] = '';
                }
            } else {
                $de['shi'] = [];
            }

            $de['sta_time'] = date('Y-m-d H:i', $de['sta_time']);
            $de['up_time']  = date('Y-m-d H:i', $de['up_time']);
            if ($de['handover']) {
                $de['handover'] = unserialize($de['handover']);
            } else {
                $de['handover'] = null;
            }

        } else {
            $de = null;
        }

        r_date($de, 200);


    }

    /*
     * 获取师傅
     */
    public function get_master()
    {
        $data                  = $this->model->post(['username']);
        $dat['username']       = $data['username'];
        $dat['order_store_id'] = $this->us['store_id'];
        $result                = send_post(UIP_SRC . "/shopowner/User/userlist", $dat);
        $results               = json_decode($result);
        if ($results->code == 200) {
            $de['chen'] = $results->data;
        } else {
            $de['chen'] = null;
        }
        r_date($de, 200);
    }

    /*
        *
        * 联系工程师
        */
    public function engineer()
    {
        $data    = $this->model->post(['order_num']);
        $results = send_post(UIP_SRC . "/shopowner/User/orderUser", $data);
        $results = json_decode($results);
        if ($results->code == 200) {
            r_date($results->data, 200);
        } else {
            r_date([], 300, $results->msg);
        }

    }

    /**
     * 开工设置
     */
    public function startup_settings()
    {
        $data = $this->model->post(['con', 'sta_time', 'up_time', 'order_id', 'shi_id', 'handover']);
        if (strtotime($data['sta_time']) > strtotime($data['up_time'])) {
            r_date([], 300, "开工时间必须早于等于完工时间");
        }
        $res = db('startup')->where(['orders_id' => $data['order_id']])->find();
        db()->startTrans();
        try {
            if ($res) {
                $o = [
                    'con' => $data['con'],//备注
                    'sta_time' => strtotime($data['sta_time']),
                    'up_time' => strtotime($data['up_time']),
                    'xiu_id' => $data['shi_id'],
                    'handover' => !empty($data['handover']) ? serialize(json_decode($data['handover'], true)) : '',//图片,
                ];
                db('startup')->where('orders_id', $data['order_id'])->update($o);
            } else {
                $res = db('startup')
                    ->insertGetId([
                        'con' => $data['con'],//备注
                        'sta_time' => strtotime($data['sta_time']),
                        'up_time' => strtotime($data['up_time']),
                        'orders_id' => $data['order_id'],
                        'xiu_id' => $data['shi_id'],
                        'handover' => !empty($data['handover']) ? serialize(json_decode($data['handover'], true)) : '',//图片,
                    ]);
                db('order')->where(['order_id' => $data['order_id'], 'assignor' => $this->us['user_id']])->update(['startup_id' => $res]);
            }

            vendor('foxyzeng.huyi.HuYiSMS');
            $sms = new HuYiSMS();
            $us  = db('order')->where('order_id', $data['order_id'])->field('order.order_no,order.ification,order.lat,order.lng,order.assignor,order.pro_id,order.addres,u.store_id,u.mobile,u.username,p.province,c.city,y.county,order.contacts,order.telephone,order.logo,order.pro_id2,st.store_name,co.con_time')
                ->join('user u', 'order.assignor=u.user_id ', 'left')
                ->join('store st', 'st.store_id=u.store_id ', 'left')
                ->join('province p', 'order.province_id=p.province_id', 'left')
                ->join('city c', 'order.city_id=c.city_id', 'left')
                ->join('county y', 'order.county_id=y.county_id', 'left')
                ->join('contract co', 'order.order_id=co.orders_id', 'left')
                ->find();
            if ($us['ification'] == 2) {
                $ca = db('envelopes')->where(['ordesr_id' => $data['order_id']])->field('give_money')->find();
                $p  = $ca['give_money'];
            } else {
                $ca = db('capital')->where(['ordesr_id' => $data['order_id'], 'types' => 1, 'enable' => 1])->field('sum(to_price),sum(give_money)')->find();
                $p  = $ca['sum(give_money)'];
            }

            $s                      = db('goods_category')->where(['id' => $us['pro_id'], 'pro_type' => 1])->find();
            $uss['title']           = !empty($s['title']) ? $s['title'] : '暂无数据';
            $uss['discount']        = $p;
            $uss['order_num']       = $us['order_no'];
            $uss['sign_time']       = $us['con_time'];
            $uss['order_id']        = $data['order_id'];
            $uss['store_id']        = $us['store_id'];
            $uss['store_name']      = $us['store_name'];
            $uss['store_mobile']    = $us['mobile'];
            $uss['start_time']      = strtotime($data['sta_time']);
            $uss['end_time']        = strtotime($data['up_time']);
            $uss['customer_name']   = $us['contacts'];
            $uss['customer_mobile'] = $us['telephone'];
            $uss['province']        = $us['province'];
            $uss['city']            = $us['city'];
            $uss['district']        = $us['county'];
            $uss['address']         = $us['addres'];
            $uss['join_imgs']       = json_decode($data['handover'], true);

            $uss['orderuser'] = explode(",", $data['shi_id']); //师傅ID
            $uss['desc']      = $data['con'];
            $uss['lat']       = $us['lat'];
            $uss['lng']       = $us['lng'];

            if ($us['logo']) {
                $uss['problemimg'] = unserialize($us['logo']);
            } else {
                $uss['problemimg'] = '';
            }
            $ussp = db('capital')->where(['ordesr_id' => $data['order_id'], 'enable' => 1, 'types' => 1])->select();
            foreach ($ussp as $k => $u) {
                $uss['problem'][$k]['problem']       = $u['wen_a'] . '->' . $u['wen_b'] . '->' . $u['wen_c'];
                $uss['problem'][$k]['title']         = $u['class_b'];
                $uss['problem'][$k]['category']      = $u['class_a'];
                $uss['problem'][$k]['unit']          = $u['company'];
                $uss['problem'][$k]['quantity']      = $u['square'];
                $uss['problem'][$k]['price']         = $u['to_price'];
                $uss['problem'][$k]['store_code_id'] = $u['capital_id'];
                unset($ussp[$k]);
                $p = db('detailed')->where(['detailed_title' => $u['class_a']])->find();
                if ($p) {
                    $p = db('detailed')->where(['detailed_title' => $u['class_b']])->value('serial');
                    if ($p) {
                        $uss['problem'][$k]['code'] = $p;
                    }
                } else {
                    $uss['problem'][$k]['code'] = '';
                }

            }
            $result  = send_post(UIP_SRC . "/shopowner/Order/receiveOrder", $uss);
            $results = json_decode($result);
            if ($results->code == 200) {
                $uscapital = db('capital')->where(['ordesr_id' => $data['order_id'], 'enable' => 1])->field('wen_c')->select();
                if ($uscapital) {
                    if ($us['pro_id2'] != 129 && $uscapital[0]['wen_c'] != '暗埋水管打压检测') {
                        if(preg_match("/^1[345678]{1}\d{9}$/",$us['telephone'])){
                            $content = "亲，感谢选择益鸟维修，已定于{$data['sta_time']}正式开工，请悉知。若需要修改开工时间或增加施工项目，请及时与工程师进行沟通~若有任何需要，请及时联系：4000987009～回T退订【益鸟维修】";
                            $sms->duan($us['telephone'], $content);
                        }

                    }
                }
                db()->commit();
                r_date([], 200, '新增成功');
            } else {
                r_date([], 300, $results->msg);
            }
        } catch (Exception $e) {
            db()->rollback();
            r_date([], 300, $e->getMessage());
        }

    }

    /**
     * 发起收款
     */
    public function payment()
    {
        $data = $this->model->post(['logos', 'weixin', 'orders_id', 'money']);

        if ($data['money'] < 0) {
            r_date([], 300, '请输入正确金额');
        }
        if ($data['weixin'] == 1 && empty($data['logos'])) {

            r_date([], 300, '请上传图片');
        }

        $res = db('payment')
            ->insertGetId([
                'uptime' => time(),//实际完工时间
                'logos' => !empty($data['logos']) ? serialize(json_decode($data['logos'], true)) : '',//图片
                'money' => $data['money'],//尾款
                'orders_id' => $data['orders_id'],
                'weixin' => $data['weixin'],
            ]);
        if ($res) {
            r_date([], 200, '新增成功');
        } else {
            r_date([], 300, '操作失败');
        }
    }


    function object2array(&$object)
    {
        $object = json_decode(json_encode($object), true);
        return $object;
    }

    public function unit()
    {
        $object = db('unit')->field('title,id')->select();

        r_date($object, 200);
    }


    /**
     * 视频节点
     */
    public function jie()
    {

        $data = $this->model->post(['order_ids']);

        //师傅节点视频;
        $shi['order_num'] = $data['order_ids'];

        $results = send_post(UIP_SRC . "/shopowner/Orderstage/stagelist", $shi);
        $results = json_decode($results);
        if ($results->code == 200) {
            r_date($results->data, 200);

        } else {
            r_date([], 200, $results->msg);
        }

    }

    /*
    *
    * 订单发起返工
    */
    public function fan()
    {
        $data = $this->model->post(['order_num', 'type', 'desc', 'yier']);

        $order             = db('order')->where('order_id', $data['order_num'])->find();
        $data['order_num'] = $order['order_no'];
        $result            = send_post(UIP_SRC . "/shopowner/Rework/orderRework", $data);
        if ($data['yier'] == 2) {
            db('order')->where('order_no', $data['order_num'])->update(['rework' => 1]);
        }
        $results = json_decode($result);
        if ($results->code == 200) {
            r_date($results->msg, 200);
        } else {
            r_date($results->msg, 300, $results->msg);
        }
    }


    private function get_time($targetTime)
    {
        // 今天最大时间
        $todayLast = strtotime(date('Y-m-d 23:59:59'));
        $agoTime   = $todayLast - $targetTime;
        $agoDay    = floor($agoTime / 86400);

        $result = 0;
        if ($agoDay == 1) {
            $result = 1;
        } elseif ($agoDay == 7) {
            $result = 7;
        } elseif ($agoDay >= 30) {
            $result = 8;
        }
        return $result;
    }

}